package com.sright.bcard.common.service.share.okhttp;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;

/**
 * okhttp工具类
 */
@Slf4j
public abstract class HttpAdapter {

    private static OkHttpClient client = new OkHttpClient();

    /**
     * 发送GET请求
     * @param url
     * @param headerMap
     * @return
     */
    protected Response doGet(String url, Map<String, String> headerMap) {
        try {
            Headers.Builder headerBuilder = new Headers.Builder();
            if (headerMap != null && !headerMap.isEmpty()) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    String name = entry.getKey();
                    String value = entry.getValue();
                    headerBuilder.add(name, value);
                }
            }
            Request request = new Request.Builder()
                    .url(url)
                    .headers(headerBuilder.build())
                    .build();
            Response response = client.newCall(request).execute();
            return response;
        } catch (IOException e) {
            log.info("ERROR@HttpAdapter.doGet:throwsException, url={}", new Object[]{
                    url,
                    e
            });
            return null;
        }
    }

    /**
     * 发送POST请求
     * @param url
     * @param jsonParams
     * @return
     */
    public static Response doPost(String url, String jsonParams) {
        try {
            OkHttpClient client = new OkHttpClient();
            MediaType MEDIA_TYPE_TEXT = MediaType.parse("application/json");
            Request request = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(MEDIA_TYPE_TEXT, jsonParams))
                    .build();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new RuntimeException("psot请求调用失败");
            } else {
                return response;
            }
        } catch (IOException e) {
            log.error("ERROR@HttpAdapter.doGet:throwsException, url={}", new Object[]{
                    url,
                    e
            });
            return null;
        }
    }

}
